package com.salon.server.service;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.salon.server.entity.Member;
import com.salon.server.entity.User;
import com.salon.server.mapper.MemberMapper;
import com.salon.server.mapper.UserMapper;
import com.salon.server.model.MessageType;
import com.salon.server.model.R;
import com.salon.server.model.UserResponse;
import com.salon.server.model.request.UserRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户基础信息表 服务实现类
 * </p>
 *
 * @author zooy
 * @since 2025-08-26
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Autowired
    private MemberMapper memberMapper;

    /**
     * 登录，判断账户密码是否错误
     */
    public R loginValid(User user) {
        // 根据登录名查询用户
        User localUser = this.baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        if (localUser == null) {
            return R.fail(MessageType.ACCOUNT_PASSWORD_ERROR);
        }

        // 校验密码
        if (!localUser.getPassword().equals(user.getPassword())) {
            return R.fail(MessageType.ACCOUNT_PASSWORD_ERROR);
        }

        // 校验通过，返回成功
        StpUtil.login(localUser.getId());
        UserResponse userResponse = new UserResponse();
        userResponse.setToken(StpUtil.getTokenValue());
        localUser.setPassword(null);
        userResponse.setUser(localUser);
        return R.success(userResponse);
    }

    public void resetPassword(UserRequest userRequest) {

        this.baseMapper.update(new LambdaUpdateWrapper<User>().set(User::getPassword, userRequest.getNewPassword())
                .eq(User::getId, userRequest.getId()));
    }

    public void saveRoleUser(User user) {

        // 如果用户角色是customer时，同步需要插入member表中
        if (user.getRole().equals("customer")) {
            Member member = new Member();
            member.setName(user.getRealName());
            member.setPhone(user.getPhone());
            member.setEmail(user.getEmail());
            memberMapper.insert(member);
            user.setOtherId(member.getId());
        }

        this.baseMapper.insert(user);
    }
}
